<template>
	<div class="box">
	  <el-form
		:model="data.ruleForm"
		:rules="rules"
		ref="ruleFormRef"
		label-width="90px"
		class="demo-ruleForm"
		size="large"
		label-position="left"
		validate-on-rule-change
		style="width: 85%"
	  >
		<el-form-item label="标题" prop="title" style="width: 100%">
		  <el-input
			style="width: 100%"
			type="text"
			v-model="data.ruleForm.title"
			placeholder="输入标题..."
		  ></el-input>
		</el-form-item>
  
		<el-form-item label="内容" prop="content" style="width: 100%">
		  <mavon-editor
			v-model="data.ruleForm.content"
			ref="md"
			@imgAdd="imgAdd"
			style="width: 100%; height: 430px"
		  />
		</el-form-item>
  
		<el-form-item label="封面" prop="coverImage">
		  <el-upload
			:action="`http://localhost:8002/file/fileoss/upload`"
			:show-file-list="false"
			:on-success="handleAvatarSuccess"
			:before-upload="beforeAvatarUpload"
			class="avatar-uploader"
		  >
			<img v-if="data.imageUrl" :src="data.imageUrl" class="avatar" />
			<!-- <el-icon v-else name="UploadFilled" class="avatar-uploader-icon"></el-icon> -->
			<el-icon v-else class="avatar-uploader-icon">
				 <UploadFilled/>
			</el-icon>
		  </el-upload>
		</el-form-item>
  
		<el-form-item label="竞赛时间" prop="competitionTime" style="width: 50%">
			<el-date-picker
     		 v-model="data.dateArr"
			 @change="dateChange"
			 value-format="YYYY-MM-DD HH:mm:ss"
    		 type="datetimerange"		
			 range-separator="-"
     		 start-placeholder="开始时间"
     		 end-placeholder="结束时间"
    		/>
		</el-form-item>

		<el-form-item label="报名截止时间" prop="registrationDeadline">
			<el-date-picker
			type="datetime"
			@change="deadlineChange"
     		 v-model="data.ruleForm.registrationDeadline"
			 placeholder="截止时间"
    		/>
		</el-form-item>

		<el-form-item style="width: 100%">
		  <div style="width: 100%; display: flex; justify-content: center">
			<el-button
			  type="primary"
			   round 
			  @click="commit(ruleFormRef)"
			>
			 <el-icon>
                <Promotion />
              </el-icon>
			  发布
			</el-button>
			<!-- <el-button @click="resetForm(ruleFormRef)">重置</el-button> -->
		  </div>
		</el-form-item>
	  </el-form>
	</div>
  </template>
  
  <script lang="ts">
  import { onMounted, defineComponent, reactive, ref } from 'vue'
  import axios from 'axios'
  import { useRouter } from 'vue-router';
  import type { FormInstance, FormRules } from 'element-plus'
  import {UploadFilled,Promotion} from '@element-plus/icons-vue'
  import { getCompetitionById } from '@/api/competition'

  export default defineComponent({
	components: {
  	  UploadFilled,Promotion
  },
	setup() {
	  //vue3获取ref
	  const ruleFormRef = ref<FormInstance>()
	  const md = ref(null)
  
	  const router = useRouter();

	  //初始竞赛信息
	  const competition = ref({});

	  const data = reactive({
		//表单
		ruleForm: {
			id: 0,
			title: '',
			coverImage: '',
			competitionTime:'',
			registrationDeadline:'',
			content: '',
		},
  
		//封面显示
		imageUrl: '',

		//竞赛时间（虚设）
		dateArr : '',
})
	  
	  //表单验证
	  const validateContent = (rule: any, value: any, callback: any) => {
		if (value === '') {
		  return callback(new Error('请输入内容！！'))
		} else {
		  callback()
		}
	  }

	  const validateCoverImage = (rule: any, value: any, callback: any) => {
		if (value === '') {
		  return callback(new Error('请上传封面！'))
		} else {
		  callback()
		}
	  }

	  const rules = reactive<FormRules<typeof data.ruleForm>>({
		title: [{ required: true, message: '请输入标题！', trigger: 'blur' }],
		competitionTime: [{ required: true, message: '请输入竞赛时间！', trigger: 'blur' }],
		registrationDeadline: [{ required: true, message: '请输入报名截止时间！', trigger: 'blur' }],
		coverImage: [
		  { required: true, validator: validateCoverImage, trigger: 'blur' },
		],
		content: [
		  { required: true, validator: validateContent, trigger: 'blur' },
		],
	  })
  
  
	  onMounted(async () => {
		getCompetition()
		
	  })
   
	  const getCompetition = async () => {
		console.log('id',router.query.id);
		try {
   			 const { data } = await getCompetitionById(router.query.id);
   			 console.log("获得竞赛信息:", data);
   			 competition.value = data.competition;
			 init()
  		} catch (error) {
   			 Promise.reject(error);
        }
	  }

	  const init =  () => {
		data.ruleForm.id   =  competition.value.id ;
		data.ruleForm.title  =  competition.value.title ;
		data.ruleForm.content   =  competition.value.content ;
		data.ruleForm.coverImage   =  competition.value.coverImage ;
		data.ruleForm.competitionTime   =  competition.value.competitionTime ;
		data.ruleForm.registrationDeadline   =  competition.value.registrationDeadline ;
	  }

	  const handleAvatarSuccess = (res, file) => {
		data.imageUrl = URL.createObjectURL(file.raw)
		console.log(res.data.url)
		data.ruleForm.coverImage = res.data.url
	  }
  
	  const beforeAvatarUpload = () => {}
  
	  // const $imgAdd
	  const imgAdd = (pos: any, file: any) => {
		console.log('上传图片：断点')
		// console.log(`${File_API.OTHER_URL}`)
		// 第一步.将图片上传到服务器.
		let formdata = new FormData()
		formdata.append('file', file)
		axios({
		  url: `http://localhost:8002/file/fileoss/upload`,
		  method: 'post',
		  data: formdata,
		  headers: { 'Content-Type': 'multipart/form-data' },
		}).then((res) => {
		  // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
		  console.log(res.data.data.url)
		  console.log(md)
		  md.value.$img2Url(pos, res.data.data.url)
		})
	  }
  
	  const commit = (formEl: FormInstance | undefined) => {
		// console.log('提交')
		if (!formEl) {
		  console.log('表单没找到')
		  return
		}
		formEl.validate(async (valid) => {
		  if (valid) {
			console.log('submit!',data.ruleForm)
			console.log(data.ruleForm.registrationDeadline)
			try {
			  const res = await competitionAdd(data.ruleForm)
			  console.log(res)
			} catch (error) {
			  Promise.reject(error)
			}
		  } else {
			console.log('error submit!')
			return false
		  }
		})
	  }

	  const dateChange = (value:any) => {
		console.log(value)
		data.ruleForm.competitionTime = `${value[0]} - ${value[1]}`;
	  }

	  const deadlineChange = (value:any) => {
		console.log(value)
		data.ruleForm.registrationDeadline = value.Format("yyyy-MM-dd hh:mm:ss");
	  }
  
	  const resetForm = (formEl: FormInstance | undefined) => {
		if (!formEl) return
		formEl.resetFields()
	  }
  
	  return {
		data,
		rules,
		handleAvatarSuccess,
		beforeAvatarUpload,
		imgAdd,
		// File_API,
		commit,
		resetForm,
		ruleFormRef,
		md,
		dateChange,
		deadlineChange
	  }
	},
  })
  </script>
  
  <style scoped>
  h1 {
	color: blue;
  }
  .box {
	display: flex;
	justify-content: center;
	width: 100%;
  }
  /* .el-form{
	  display: flex;
	  align-items: center;
	  flex-direction: column;
	 
	} */
  .tag {
	margin: 10px;
  }
  </style>
  
  <!-- 饿了么的样式写在这里避免不生效 -->
  <style>
  .avatar-uploader .el-upload {
	border: 1px dashed #807d7d;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
	border-color: #409eff;
  }
  .avatar-uploader-icon {
	font-size: 28px;
	color:#409eff;
	width: 150px;
	height: 150px;
	line-height: 150px;
	text-align: center;
  }
  .avatar {
	width: 178px;
	height: 178px;
	display: block;
  }

  </style>
